package com.bw.android.bwgao6week2a.fragment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.bw.android.bwgao6week2a.AppInstance;
import com.bw.android.bwgao6week2a.R;
import com.bw.android.bwgao6week2a.WatchLiveActivity;
import com.bw.android.bwgao6week2a.adapter.LiveAdapter;
import com.bw.android.bwgao6week2a.databinding.FragmentHomeBinding;
import com.bw.android.bwgao6week2a.vm.LiveListViewModel;
import com.bw.android.network.RequestClient;
import com.bw.android.network.bean.LiveListBean;
import com.bw.android.network.bean.NewsBannerBean;
import com.bw.ch.baselib.BaseBindingFragment;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.stx.xhb.xbanner.XBanner;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class HomeFragment extends BaseBindingFragment<FragmentHomeBinding> {
    private Disposable mDisposable;
    private LiveAdapter mAdapter;
    private final List<LiveListBean.ResultBean> mData = new ArrayList<>();
    private final List<NewsBannerBean.ResultBean> mBannerData = new ArrayList<>();
    /**
     * 当前页
     */
    private int pageNo = 1;
    /**
     * 每次请求10条数据
     */
    private int rows = 10;

    private LiveListViewModel mViewModel;
    private boolean isLoadMore;

    public HomeFragment() {
        super(true);
    }

    @Override
    public int getLayout() {
        return R.layout.fragment_home;
    }

    @Override
    public void initView() {
        Log.d(AppInstance.TAG, "首页Fragment initView");
        LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext(), LinearLayoutManager.VERTICAL, false);
        mBinding.rvVideos.setLayoutManager(layoutManager);
        mBinding.rvVideos.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                isLoadMore = false;
                loadData();
            }

            @Override
            public void onLoadMore() {
                isLoadMore = true;
                loadData();
            }
        });
        mAdapter = new LiveAdapter(mData, 1);
        mBinding.rvVideos.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(position -> {
            WatchLiveActivity.open(this.getContext(), mData.get(position));
        });
        mBinding.banner.setmAdapter(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, View view, int position) {
                //剪裁Banner图片，防止图片被拉伸变形。
                ((ImageView) view).setScaleType(ImageView.ScaleType.CENTER_CROP);
                Glide.with(HomeFragment.this)
                        .load(mBannerData.get(position).getImageUrl())
                        .into((ImageView) view);
            }
        });
        mViewModel = new ViewModelProvider(this).get(LiveListViewModel.class);
        mBinding.setListVm(mViewModel);
        //观察LiveListViewModel中的liveListData
        mViewModel.liveListData.observe(this, new Observer<LiveListBean>() {
            @Override
            public void onChanged(LiveListBean liveListBean) {
                //网络请求成功
                if (isLoadMore) {
                    if (liveListBean.getResult().isEmpty()) {
                        //通知XRecyclerView没有更多数据
                        mBinding.rvVideos.setNoMore(true);
                        //如果加载更多时，没有更多数据，需要使pageNo回退到之前的值
                        --pageNo;
                    } else {
                        //通知XRecyclerView已完成加载更多
                        mBinding.rvVideos.loadMoreComplete();
                    }
                } else {
                    //通知XRecyclerView已完成下拉刷新
                    mBinding.rvVideos.refreshComplete();
                }
                mData.addAll(liveListBean.getResult());
                //刷新列表
                mAdapter.notifyDataSetChanged();

            }
        });
        //观察LiveListViewModel中的throwData
        mViewModel.throwData.observe(this, throwable -> {
            //网络请求错误时的处理
            Toast.makeText(HomeFragment.this.getContext(), throwable.toString(), Toast.LENGTH_SHORT).show();
            if (isLoadMore) mBinding.rvVideos.loadMoreComplete();
            else mBinding.rvVideos.refreshComplete();
        });
    }

    @Override
    public void initData() {
        isLoadMore = false;
        loadData();
        //请求新闻的轮播图API
        RequestClient.buildService().getBannerList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(newsBannerBean -> {
                    Log.d(AppInstance.TAG, newsBannerBean.getResult().toString());
                    mBannerData.clear();
                    mBannerData.addAll(newsBannerBean.getResult());
                    mBinding.banner.setData(mBannerData, null);
                }, throwable -> {
                    Log.d(AppInstance.TAG, throwable.toString());
                });

    }

    private void loadData() {
        if (!isLoadMore) {
            mData.clear();
        } else {
            ++pageNo;
        }
        mViewModel.loadData(pageNo, rows);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDisposable != null) mDisposable.dispose();
    }
}